package utils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.OValException;
import play.exceptions.UnexpectedException;
import play.utils.Utils.AlternativeDateFormat;

/**
 * Custom annotation handler to check if the entered date is greater than or
 * equal to the current one
 * 
 */
public class CustomInFutureCheck extends AbstractAnnotationCheck<CustomInFuture> {

	final static String mes = "validation.custom.future";

	Date reference;

	@Override
	public void configure(CustomInFuture future) {
		try {
			// done to set the date to 00:00:00 00
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			this.reference = future.value().equals("") ? cal.getTime() : AlternativeDateFormat.getDefaultFormatter()
					.parse(future.value());
		} catch (ParseException ex) {
			throw new UnexpectedException("Cannot parse date " + future.value(), ex);
		}
		if (!future.value().equals("") && future.message().equals(mes)) {
			setMessage("validation.after");
		} else {
			setMessage(future.message());
		}
	}

	@Override
	public boolean isSatisfied(Object validatedObject, Object value, OValContext context, Validator validator)
			throws OValException {
		if (value == null) {
			return true;
		}
		if (value instanceof Date) {
			if (reference.equals((Date) value)) {
				return true;
			}
			try {
				return reference.before((Date) value);
			} catch (Exception e) {
				return false;
			}
		}
		return false;
	}

}
